import React, {useEffect} from 'react'

interface PageNavProps {
  className?: string
  onScroll?: (event: any) => void
  isNoBorderTop?: boolean
  activeElementId?: string
  isWrap?: boolean
  navRef?: any
  id: string
}

const PageNav: React.FC<PageNavProps> = ({
  className,
  isNoBorderTop,
  children,
  onScroll,
  activeElementId,
  isWrap,
  navRef,
  id,
}): React.ReactElement => {
  useEffect(() => {
    const element = document.getElementById('container-nav' + (id ? id : ''))
    if (activeElementId) {
      const activeElement = document.getElementById(activeElementId)
      if (activeElement) {
        activeElement.scrollIntoView()
      }
    }

    let pos = {top: 0, left: 0, x: 0, y: 0}

    const mouseDownHandler = (e: any) => {
      element.style.cursor = 'grabbing'
      element.style.userSelect = 'none'
      pos = {
        left: element.scrollLeft,
        top: element.scrollTop,
        x: e.clientX,
        y: e.clientY,
      }

      document.addEventListener('mousemove', mouseMoveHandler)
      document.addEventListener('mouseup', mouseUpHandler)
    }

    const mouseMoveHandler = (e: any) => {
      const dx = e.clientX - pos.x
      const dy = e.clientY - pos.y
      element.scrollTop = pos.top - dy
      element.scrollLeft = pos.left - dx
    }

    const mouseUpHandler = function () {
      element.style.cursor = 'grab'
      element.style.removeProperty('user-select')

      document.removeEventListener('mousemove', mouseMoveHandler)
      document.removeEventListener('mouseup', mouseUpHandler)
    }

    element.addEventListener('mousedown', mouseDownHandler)
  }, [activeElementId])

  return (
    <nav
      ref={navRef}
      id={'container-nav' + (id ? id : '')}
      onScroll={onScroll}
      className={
        'page-nav ' +
        (isWrap ? 'wrap ' : 'no-wrap ') +
        (isNoBorderTop ? 'non-border-top ' : '') +
        ' ' +
        (className ? ' ' + className : '')
      }>
      {children}
    </nav>
  )
}

export {PageNav}
